package com.bcn.login_mybatis_demo.config;

import com.bcn.login_mybatis_demo.security.SecurityUserHolder;
import com.bcn.login_mybatis_demo.util.JwtTokenUtils;
import com.bcn.login_mybatis_demo.util.ResultUtil;
import com.google.gson.Gson;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import com.bcn.login_mybatis_demo.annotation.PassToken;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtAuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;

            // 检查方法上是否有@PassToken注解
            if (handlerMethod.getMethodAnnotation(PassToken.class) != null) {
                return true; // 如果有@PassToken注解，则跳过Token验证
            }

            String authorizationHeader = request.getHeader(JwtTokenUtils.TOKEN_HEADER);
            // 如果请求头中没有token，则返回未授权的错误
            if (authorizationHeader == null || !authorizationHeader.startsWith(JwtTokenUtils.TOKEN_PREFIX)) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json");
                String jsonResponse = new Gson().toJson(ResultUtil.noToken("token必传"));
                response.getWriter().write(jsonResponse);
                return false;
            }

            // 提取短Token
            String token = authorizationHeader.substring(JwtTokenUtils.TOKEN_PREFIX.length()).trim();
            try {
                // 验证短Token
                Integer userId = JwtTokenUtils.verifyShortToken(token);
                if (userId == null) {
                    throw new Exception("Token is invalid or has expired.");
                }
                SecurityUserHolder.setCurrentUserId(Long.valueOf(userId));

                // 如果Token验证通过，则继续执行后续操作
                return true;
            } catch (Exception e) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json");
                String jsonResponse = new Gson().toJson(ResultUtil.noToken("token必传"));
                response.getWriter().write(jsonResponse);
                return false;
            }
        }
        return false; // 默认情况下，如果请求不符合要求，则不继续处理
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求处理结束后，清除当前用户ID
        SecurityUserHolder.clear();
    }
}
